package com.yesep.learn.design.structural.proxy;


import java.lang.reflect.*;

/**
 * 动态态代理
 */
public class DynamicLoggerProxy implements InvocationHandler, ILogger {
    private final ILogger target;

    public DynamicLoggerProxy(ILogger target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //System.out.println("Before logging...");
        Object result = method.invoke(target, args);
        //System.out.println("After logging...");
        return result;
    }

    public ILogger getProxy() {
        return (ILogger) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this
        );
    }

    @Override
    public void log(String message) {
        getProxy().log(formatMessage(message));
    }

    private String formatMessage(String message) {
        // 格式化日志消息
        return "[Dynamic Logger][" + getCurrentTime() + "] " + message;
    }
}